<?php

use app\model\Config;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

/**
 * 密码加密算法
 * @param $value 需要加密的值
 * @return mixed
 */
function password($value)
{
    $value = sha1('open_v1_') . md5($value) . md5('_encrypt') . sha1($value);
    return sha1($value);
}

/**
 * 二位数组重新组合数据
 * @param $array
 * @param $key
 * @return array
 */
function array_format_key($array, $key)
{
    $newArray = [];
    foreach ($array as $vo) {
        $newArray[$vo[$key]] = $vo;
    }
    return $newArray;
}

/*获取当前域名域名*/
function get_home_url() {
    return request()->domain();
}

/**
 * 获取图片完整链接
 * @param $image_path
 * @return mixed|string
 */
function get_image_url($image_path) {
    if (empty($image_path) || str_contains($image_path, 'http')) {
        return $image_path;
    }
    return get_home_url().$image_path;
}

/**
 * 获取图片完整链接数组
 * @param $image_path
 * @return array
 */
function get_image_url_arr($image_path) {
    $arr = $image_path ? explode(',', $image_path) : [];
    $list = [];
    foreach ($arr as $v) {
        $ret = get_image_url($v);
        if ($ret) {
            $list[] = $ret;
        }
    }
    return $list;
}

/**
 * 获取图片路径
 * @param $image_url
 * @return array|string|string[]
 */
function get_image_path($image_url) {
    return str_replace(get_home_url(), '', $image_url);
}

/**
 * 当前当时时间戳
 * @return int|mixed
 */
function now_time() {
    static $now_time;
    if (!isset($now_time)) {
        $now_time = time();
    }
    return $now_time;
}

/**
 * 生成Excel文件并保存到指定路径
 * @param $list
 * @param $field_names
 * @return string
 */
function generateExcelFile($list, $field_names)
{
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    $key = 0;
    foreach ($field_names as $field => $header) {
        $column = chr(65 + $key); // 从 'A' 开始
        $sheet->setCellValue($column . '1', $header);

        // 填充数据
        foreach ($list as $rowIndex => $row) {
            if (isset($row[$field])) {
                $value = is_array($row[$field]) ? json_encode($row[$field], JSON_UNESCAPED_UNICODE) : $row[$field];
                $sheet->setCellValue($column . ($rowIndex + 2), $value); // 数据从第2行开始
            }
        }
        $key++;
    }

    // 创建 Xlsx 文件并保存到指定路径
    $writer = new Xlsx($spreadsheet);

    $file_name = date('YmdHis').rand(1000,9999).'.xlsx';
    $filePath = public_path().'export'.DIRECTORY_SEPARATOR.$file_name;
    $writer->save($filePath);

    return get_home_url().'/export/'.$file_name;
}


/**
 * redis锁
 * @param $key
 * @param $timeOut
 * @return bool
 */
function redisLock($key, $timeOut = 60)
{
    if (!$key) {
        return false;
    }
    $key .= '_lock';
    $redis = \think\facade\Cache::store('redis');
    $nx = $redis->handler()->setnx($key, 1);
    if (!$nx) {
        return false;
    }
    $redis->expire($key, $timeOut);
    return true;
}

/**
 * redis 解锁
 * @param $key
 * @return bool
 */
function redisUnLock($key)
{
    if (!$key) {
        return false;
    }
    $key .= '_lock';
    $redis = \think\facade\Cache::store('redis');
    $redis->del($key);
    return true;
}

/**
 * 获取配置
 * @param string $key
 * @return mixed
 */
function get_config($key="") {
    return (new Config())->get($key);
}

/**
 * @param $url
 * @return mixed
 */
function curl_get($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);           // 请求地址
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回内容作为字符串
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 HTTPS 证书验证（根据需要）
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);         // 超时时间（秒）
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

/**
 * @param $url
 * @return mixed
 */
function curl_post($url, $data, $is_json=true, $header = []) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true); // 启用 POST
    if ($is_json) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        // 设置 JSON 请求头
        curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge([
            'Content-Type: application/json',
            'Content-Length: ' . strlen(json_encode($data))
        ],$header));
    } else {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // 数据格式为 key=value&key=value
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);
    if(curl_errno($ch)) {
        //echo 'Curl error: ' . curl_error($ch);
    }
    curl_close($ch);
    return json_decode($response, true);
}
